//
//  HTTPRequest.swift
//  DYSwiftFramework
//
//  Created by 黄德玉 on 2018/8/6.
//  Copyright © 2018年 none. All rights reserved.
//

import Alamofire

enum HTTPError : Error{
    case serverError(code:Int?,description:String)
    case dataError(code:Int?,description:String)
}

class HTTPRequest{
    public var baseURL:URLConvertible?
    // 请求适配器
    public var adapter:AdaptHandler?
    // 重试机制
    public var retryHander:RetryHandler?
    // 入口参数包装
    public var wrapperPars:((Parameters?)->Parameters?)?
    // 响应数据解包
    public var reponseUnwrapper:((Any)->Result<Any?,HTTPError>)?
    // 响应数据处理,处理的是解包后的数据
    public var onResponse:((Any?,Error?)->Void)?
    public var onResponseData:((Data?,Error?)->Void)?
    
    // 按照json的形式返回
    func response(_ r:((Any?,Error?)->Void)?)  {
        onResponse = r
    }
    
    // 按照data的形式返回
    func responseData(_ r:((Data?,Error?)->Void)?) {
        onResponseData = r
    }
    
    private weak var _request:Request?
    
    var afDataRequest:DataRequest? {
        get {
            return _request as? DataRequest
        }
        set(v) {
            _request = v
        }
    }
    
    var afDownloadRequest:DownloadRequest? {
        get {
            return _request as? DownloadRequest
        }
        set(v){
            _request = v
        }
    }
    
    // 取消网络
    func cancel()  {
        _request?.cancel()
    }
}

// 请求类型，目前只有一个，后面有新增需要扩展
enum HostType {
    enum SubType{
        case main
        case live // 直播
        case advocacy // 代言
    }
    case main(subType:SubType)    // 域名部分一致，包装和解包数据逻辑一致
    
    func value() -> String {
        var host = ""
        switch self {
        case .main(subType: .main):
            switch APP_Environment {
            case .online:
                host = "sc"
            case .test1:
                host = "sc"
            }
        case .main(subType: .live):
            switch APP_Environment {
            case .online:
                host = "sa"
            case .test1:
                host = "t-do-dev"
            }
        case .main(subType: .advocacy):
            switch APP_Environment {
            case .online:
                host = "sa"
            case .test1:
                host = "t-do-dev"
            }
        }
        return host
    }
    
}

extension HTTPRequest{
    static func defaultDataRequest(_ path:String, parameters:Parameters?,method:HTTPMethod = .get, retryCount:Int,host:HostType) -> HTTPRequest {
        let req = HTTPRequest()
        
        req.baseURL = "https://\(host.value()).xxxxxx.com"

        // 请求适配器
        req.adapter = { (req, session, completion) in
            var request = req
            if USER.isLogin {
                request.headers.add(name: "Cookie", value: "ticket|\(USER.ticket ?? "")")
            }
            completion(.success(request))
        }
        // 重试机制
        req.retryHander = { (req, session, error, completion) in
            // 请求超时，3s后重试
            if req.response?.statusCode == 408 && req.retryCount < retryCount {
                completion(.retryWithDelay(3))
                return
            }
            completion(.doNotRetry)
        }
        // 包装请求参数
        req.wrapperPars = { pars in
            var newPars = pars
            newPars?["appCont"] = 1
            newPars?["strVersion"] = 0
            return newPars
        }
        
        // 响应解包
        req.reponseUnwrapper = { data in
            if JSONSerialization.isValidJSONObject(data) {
                if let reslut = data as? [String: Any?] {
                    if let code = reslut["errorCode"] as? Int {
                        if code != 0 {
                            return .failure(.dataError(code: code, description: "数据出错"))
                        }
                    } else {
                        return .failure(.dataError(code: -1, description: "数据出错"))
                    }
                    // 作为字典返回
                    if let content = reslut["data"]{
                        return .success(content)
                    } else {
                        return .success(nil)
                    }
                } else {
                    return .failure(.dataError(code: -2, description: "数据出错"))
                }
            } else {
                return .success(nil)
            }
        }
        return req
    }
        
}
